// function UsersService() {
// }
// 属性放在实例上 方法放在原型上
// new UsersService() // new 实例化 {} oop
// 继承 封装 多态 

const { exec } = require('../db/index');
class UsersService {
  // constructor() {
  //   super() // 执行 父类
  // }
  async page(ctx) {
    const { page, size } = ctx.query;
    if (page && size) {
      const list = await exec(`select count(id) as num from blogs`)
      console.log(list, 'list')// [{num:15}]
      const data = await exec(`select * from blogs order by id desc limit ${size} offset ${page * size}`)
      return { code: 0, msg: 'success', total: list[0].num, data };
    } else {
      const data = await exec(`select * from blogs`)
      return { code: 0, msg: 'success', data };
    }
  }  // page 原型上
  async delete(ctx) {
    const { id } = ctx.params;
    const data = await exec(`delete from blogs where id =?`, [id])
    return { code: 0, msg: 'success', data };
  }

  async search(ctx) {
    const { keyword } = ctx.query;
    console.log(`select * from users where title like '%${keyword}%'`, '---sql')
    const data = await exec(`select * from users where title like '%${keyword}%'`)
    return { code: 0, msg: 'success', data };
  }

  async update(ctx) {
    const { id } = ctx.params;
    const { title, content, author, userid } = ctx.request.body
    const data = await exec(`update users set title=?,content=?,author=?,userid=? where id = ?`,
      [title, content, author, userid, id])
    return { code: 0, msg: 'success', data };
  }
  async add(ctx) {
    console.log(ctx.request.body, 'body----body')
    const { title, content, createTime, author, userid } = ctx.request.body
    const data = await exec(`insert into blogs (title, content, createTime, author, userid) values (?,?,?,?,?)`,
      [title, content, createTime, author, userid])
    return { code: 0, msg: 'success', data };
  }
}

module.exports = new UsersService